package com.rc.saas.mini.service.market;

import com.alibaba.fastjson.JSON;
import com.rc.saas.mini.common.constant.WebConstant;
import com.rc.saas.mini.common.mq.MqConfig;
import com.rc.saas.mini.common.mq.MqProducer;
import com.rc.saas.mini.mapper.market.MarketActivityMapper;
import com.rc.saas.mini.mapper.market.MarketActivityMemberMapper;
import com.rc.saas.mini.mapper.market.MarketActivityTicketMapper;
import com.rc.saas.mini.mapper.member.MemberAccountRecordMapper;
import com.rc.saas.mini.mapper.member.MemberInfoMapper;
import com.rc.saas.mini.mapper.member.MemberTicketMapper;
import com.rc.saas.mini.mapper.ticket.TenantTicketSendRecordMapper;
import com.rc.saas.mini.mapper.ticket.TenantTicketTypeMapper;
import com.rc.saas.mini.model.market.*;
import com.rc.saas.mini.model.member.*;
import com.rc.saas.mini.model.recharge.RechargeOrder;
import com.rc.saas.mini.model.tenant.TenantTicketSendRecord;
import com.rc.saas.mini.model.tenant.TenantTicketType;
import com.rc.saas.mini.model.tenant.TenantTicketTypeExample;
import com.rc.saas.mini.service.member.MemberAccountRecordService;
import com.rc.saas.mini.service.member.MemberAccountService;
import com.rc.saas.mini.service.member.MemberInfoService;
import com.rc.saas.mini.service.member.MemberTicketService;
import com.rc.saas.mini.vo.market.MarketActivityTicketVo;
import com.rc.saas.mini.vo.market.MarketActivityVo;
import com.rc.saas.mini.vo.market.MarketActivityVo2;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;


/**
 * @author wangzhengwei
 * @create 2021/4/30
 */
@Service
public class MarketActivityServiceImpl implements MarketActivityService {
    @Autowired
    private MarketActivityMapper marketActivityMapper;

    @Autowired
    private MarketActivityRecordService marketActivityRecordService;

    @Autowired
    private MemberInfoMapper memberInfoMapper;

    @Autowired
    private MarketActivityMemberMapper marketActivityMemberMapper;

    @Autowired
    private TenantTicketTypeMapper tenantTicketTypeMapper;

    @Autowired
    private TenantTicketSendRecordMapper tenantTicketSendRecordMapper;

    @Autowired
    private MemberTicketService memberTicketService;

    @Autowired
    private MarketActivityTicketMapper marketActivityTicketMapper;

    @Autowired
    private MemberTicketMapper memberTicketMapper;

    @Autowired
    private MarketActivityMemberService marketActivityMemberService;

    @Autowired
    private MemberAccountService memberAccountService;

    @Autowired
    private MemberAccountRecordMapper memberAccountRecordMapper;

    @Autowired
    private MemberAccountRecordService memberAccountRecordService;


    @Autowired
    private MemberInfoService memberInfoService;

    @Autowired
    private MqProducer mqProducer;

    @Override
    public MarketActivityMapper getMapper() {
        return marketActivityMapper;
    }

    @Override
    public List<MarketActivityVo> listByTenant(String tenantCode, String sendType, String activityType) {
        return Optional.ofNullable(marketActivityMapper.listByTenant(tenantCode, sendType, activityType)).orElseGet(() -> null);
    }

    //@Override
    //public void sendChargeTicketByMarketActivity(Long memberId, BigDecimal amount, String tenantCode, String activityType, Long rechargeOrderId) {
    //    MemberInfo memberInfo = memberInfoMapper.selectByPrimaryKey(memberId);
    //    String sendType;
    //    if ("0".equals(memberInfo.getMemberType())) {
    //        sendType = "2";
    //    } else if ("3".equals(memberInfo.getMemberType())) {
    //        sendType = "-1";
    //    } else {
    //        sendType = "3";
    //    }
    //    List<MarketActivityVo> marketActivityVos = listByTenant(tenantCode, sendType, activityType);
    //    marketActivityVos.sort(Comparator.comparing(MarketActivityVo::getRequireAmount).reversed());
    //    if (marketActivityVos != null && marketActivityVos.size() > 0){
    //        //活动次数
    //        MarketActivityMemberExample marketActivityMemberExample = new MarketActivityMemberExample();
    //        marketActivityMemberExample.createCriteria().andMemberIdEqualTo(memberId).andMarketActivityIdEqualTo(marketActivityVos.get(0).getMarketActivityId()).andTenantCodeEqualTo(tenantCode);
    //        Long count = marketActivityMemberMapper.countByExample(marketActivityMemberExample);
    //        if (count < marketActivityVos.get(0).getMaxDiscountCount()){
    //            //符合则赠送优惠券
    //            for (MarketActivityVo marketActivityVo : marketActivityVos) {
    //                if (amount.compareTo(marketActivityVo.getRequireAmount()) != -1) {
    //                    //insert 优惠券  marketActivityMember  member_ticket
    //                    MarketActivityMember marketActivityMember = new MarketActivityMember();
    //                    marketActivityMember.setTenantCode(tenantCode);
    //                    marketActivityMember.setMemberId(memberId);
    //                    marketActivityMember.setMarketActivityId(marketActivityVo.getMarketActivityId());
    //                    marketActivityMember.setTicketTypeId(marketActivityVo.getTicketTypeId());
    //                    marketActivityMember.setRechargeOrderId(rechargeOrderId);
    //                    marketActivityMember.setGainCount(count.intValue() + 1);
    //                    marketActivityMember.setCreatedBy("WX" + tenantCode);
    //                    marketActivityMember.setCreatedTime(new Date());
    //                    marketActivityMemberMapper.insertSelective(marketActivityMember);
    //                    TenantTicketType tenantTicketType = tenantTicketTypeMapper.selectByPrimaryKey(marketActivityVo.getTicketTypeId());
    //                    if (tenantTicketType != null) {
    //                        //todo 发放优惠券记录表
    //                        TenantTicketSendRecord tenantTicketSendRecord = new TenantTicketSendRecord();
    //                        tenantTicketSendRecord.setTenantCode(tenantCode);
    //                        tenantTicketSendRecord.setTicketTypeId(tenantTicketType.getTicketTypeId());
    //                        tenantTicketSendRecord.setSendCount(marketActivityVo.getSendCount());
    //                        tenantTicketSendRecord.setSendTime(new Date());
    //                        tenantTicketSendRecord.setSendType("0");
    //                        tenantTicketSendRecord.setCreatedBy("WX" + tenantCode);
    //                        tenantTicketSendRecord.setCreatedTime(new Date());
    //                        tenantTicketSendRecordMapper.insertReturnId(tenantTicketSendRecord);
    //                        for (int i = 0; i < marketActivityVo.getSendCount(); i++) {
    //                            memberTicketService.SendCoupons(tenantTicketType.getTicketTypeId(), tenantTicketSendRecord.getTicketSendRecordId(), memberId, tenantCode);
    //                        }
    //
    //                    }
    //                    break;
    //                }
    //            }
    //        }
    //
    //    }
    //}

    @Override
    public List<MarketActivityVo> listActivity(String tenantCode, Long memberId, String sendType, String activityType) {
        List<MarketActivityVo> list = marketActivityMapper.listByTenant(tenantCode, sendType, activityType);

        for (MarketActivityVo vo : list) {
            List<MarketActivityTicketVo> ticketVos = marketActivityTicketMapper.listByActivityId(vo.getMarketActivityId());
            //活动次数
            MarketActivityMemberExample marketActivityMemberExample = new MarketActivityMemberExample();
            marketActivityMemberExample.createCriteria()
                    .andMemberIdEqualTo(memberId)
                    .andMarketActivityIdEqualTo(vo.getMarketActivityId())
                    .andTenantCodeEqualTo(tenantCode);
            Long count = marketActivityMemberMapper.countByExample(marketActivityMemberExample);
            vo.setCount(count);
            vo.setMarketActivityTicketVoList(ticketVos);
        }
        return list;
    }

    @Override
    public List<MarketActivity> listCurrentActivity(String tenantCode, String sendType, String rewardType, String activityType) {
        return marketActivityMapper.listCurrentActivity(tenantCode, sendType, rewardType, activityType);
    }

    @Override
    public List<MarketActivityVo2> listActivityRuleWithGive(String activityIndex, String tenantCode, Long memberId) {
        List<MarketActivity> list = marketActivityMapper.listActivityRuleWithGive(activityIndex, tenantCode, memberId);

        if (list.size() == 0) {
            return null;
        }
        List<Long> ids = list.stream().map(MarketActivity::getTicketTypeId).distinct().collect(Collectors.toList());
        TenantTicketTypeExample tenantTicketTypeExample = new TenantTicketTypeExample();
        tenantTicketTypeExample.createCriteria().andTicketTypeIdIn(ids);
        List<TenantTicketType> tenantTicketTypes = tenantTicketTypeMapper.selectByExample(tenantTicketTypeExample);

        List<MarketActivityVo2> data = new ArrayList<>();

        for (MarketActivity marketActivity : list) {
            MarketActivityVo2 marketActivityVo2 = new MarketActivityVo2();
            BeanUtils.copyProperties(marketActivity, marketActivityVo2);


            boolean isLimit = true;
            if (memberId != null) {
                //活动次数
                MarketActivityMemberExample marketActivityMemberExample = new MarketActivityMemberExample();
                marketActivityMemberExample.createCriteria()
                        .andMemberIdEqualTo(memberId)
                        .andMarketActivityIdEqualTo(marketActivity.getMarketActivityId())
                        .andTenantCodeEqualTo(tenantCode);
                int count = (int) marketActivityMemberMapper.countByExample(marketActivityMemberExample);
                isLimit = count >= marketActivity.getMaxDiscountCount() ? false : true;
                marketActivityVo2.setCount(marketActivity.getMaxDiscountCount().intValue() - count);
                marketActivityVo2.setJoin(count);
            }
            //if (isLimit) {

            marketActivityVo2.setTenantTicketType(tenantTicketTypes.stream().filter(t -> marketActivity.getTicketTypeId().equals(t.getTicketTypeId())).findFirst().orElseGet(() -> null));
            data.add(marketActivityVo2);
            //}
        }
        return data;
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean insertActivityTicket(Long marketActivityId, MemberInfo member) {
        MarketActivity marketActivity = marketActivityMapper.selectByPrimaryKey(marketActivityId);

        if (!"2".equals(marketActivity.getActivityType())) {
            return false;
        }
        TenantTicketType tenantTicketType = tenantTicketTypeMapper.selectByPrimaryKey(marketActivity.getTicketTypeId());
        //活动次数
        MarketActivityMemberExample marketActivityMemberExample = new MarketActivityMemberExample();
        marketActivityMemberExample.createCriteria()
                .andMemberIdEqualTo(member.getMemberId())
                .andMarketActivityIdEqualTo(marketActivityId)
                .andTenantCodeEqualTo(member.getTenantCode());
        int count = (int) marketActivityMemberMapper.countByExample(marketActivityMemberExample);
        boolean isLimit = count >= marketActivity.getMaxDiscountCount() ? false : true;
        if (isLimit) {
            //用户获取用户券
            MarketActivityMember marketActivityMember = marketActivityMemberAdd(member, marketActivityId, null);
            allTicketDataAdd(member, tenantTicketType, marketActivity.getSendCount(), null, marketActivityMember);
            return true;
        }
        return false;
    }

    @Override
    public List<MarketActivityVo2> listHistoryActivityRuleWithGive(String tenantCode, Long memberId) {
        List<MarketActivity> list = marketActivityMapper.listActivityRuleWithGive(null, tenantCode, memberId);

        if (list.size() == 0) {
            return null;
        }
        List<Long> ids = list.stream().map(MarketActivity::getTicketTypeId).distinct().collect(Collectors.toList());
        TenantTicketTypeExample tenantTicketTypeExample = new TenantTicketTypeExample();
        tenantTicketTypeExample.createCriteria().andTicketTypeIdIn(ids);
        List<TenantTicketType> tenantTicketTypes = tenantTicketTypeMapper.selectByExample(tenantTicketTypeExample);

        List<MarketActivityVo2> data = new ArrayList<>();

        for (MarketActivity marketActivity : list) {
            MarketActivityVo2 marketActivityVo2 = new MarketActivityVo2();
            BeanUtils.copyProperties(marketActivity, marketActivityVo2);

            marketActivityVo2.setCount(marketActivity.getMaxDiscountCount());
            boolean isLimit = true;
            if (memberId != null) {
                //活动次数
                MarketActivityMemberExample marketActivityMemberExample = new MarketActivityMemberExample();
                marketActivityMemberExample.createCriteria()
                        .andMemberIdEqualTo(memberId)
                        .andMarketActivityIdEqualTo(marketActivity.getMarketActivityId())
                        .andTenantCodeEqualTo(tenantCode);
                int count = (int) marketActivityMemberMapper.countByExample(marketActivityMemberExample);
                isLimit = count >= marketActivity.getMaxDiscountCount() ? false : true;
                marketActivityVo2.setCount(marketActivity.getMaxDiscountCount().intValue() - count);
            }
            marketActivityVo2.setTenantTicketType(tenantTicketTypes.stream().filter(t -> marketActivity.getTicketTypeId().equals(t.getTicketTypeId())).findFirst().orElseGet(() -> null));
            data.add(marketActivityVo2);
        }
        return data;
    }

    /**
     * 拉新活动
     *
     * @param memberId
     */
    @Override
    public void activityAddMember(Long memberId) {
        //查看用户可以参与的活动(拥有参与次数的)
        MemberInfo memberInfo = memberInfoMapper.selectByPrimaryKey(memberId);

        List<MarketActivity> listActivityRule = marketActivityMapper.listActivityRuleWithGiveJoin(null, memberInfo.getTenantCode(), memberInfo.getMemberId())
                .stream().filter(data -> "5".equals(data.getActivityType())).collect(Collectors.toList());
        List<Long> ids = listActivityRule.stream().map(MarketActivity::getMarketActivityId).collect(Collectors.toList());
        List<MarketActivityRecord> marketActivityRecordList = new ArrayList<>();

        if (ids.size() > 0) {
            MarketActivityRecordExample marketActivityRecordExample = new MarketActivityRecordExample();
            marketActivityRecordExample.createCriteria().andMarketActivityIdIn(ids);
            marketActivityRecordList = marketActivityRecordService.selectByExample(marketActivityRecordExample);
        }
        MemberInfoExample memberInfoExample = new MemberInfoExample();
        memberInfoExample.createCriteria().andRecommenderIdEqualTo(memberId);

        List<MemberInfo> memberInfoList = memberInfoService.selectByExample(memberInfoExample);
        for (MarketActivity marketActivity : listActivityRule) {
            //3.拉新活动参与
            //4.数据录入（送优惠券，送金额）
            List<MarketActivityRecord> currentList = marketActivityRecordList.stream()
                    .filter(data -> "2".equals(data.getGearType())
                            && marketActivity.getMarketActivityId().equals(data.getMarketActivityId())
                            && data.getPullNew() != null && data.getPullNew().intValue() == memberInfoList.size()).collect(Collectors.toList());

            //活动次数
            MarketActivityMemberExample marketActivityMemberExample = new MarketActivityMemberExample();
            marketActivityMemberExample.createCriteria()
                    .andMemberIdEqualTo(memberId)
                    .andMarketActivityIdEqualTo(marketActivity.getMarketActivityId());
            //int count = (int) marketActivityMemberMapper.countByExample(marketActivityMemberExample);
            MarketActivityMember marketActivityMember=marketActivityMemberMapper.selectByExample(marketActivityMemberExample).stream().findFirst().orElseGet(()->null);
            //if (currentList.size() <= count) {
            //    continue;
            //}

            //参与次数不能大于总量
            if (marketActivityMember!=null&&currentList.size() <marketActivityMember.getGainCount()) {
                continue;
            }
            for (MarketActivityRecord marketActivityRecord : currentList) {
                //活动送金额
                if (marketActivityRecord.getAwardAmount() != null) {
                    MemberAccount memberAccount = memberAccountService.selectByPrimaryKey(memberId);
                    memberAccount.setAccount(memberAccount.getAccount().add(new BigDecimal(marketActivityRecord.getAwardAmount())));
                    memberAccount.setAllRechargeAmount(memberAccount.getAllRechargeAmount().add(new BigDecimal(marketActivityRecord.getAwardAmount())));
                    memberAccount.setLastUpdatedTime(new Date());
                    memberAccountService.updateByPrimaryKeySelective(memberAccount);

                    //3 新增余额变动记录
                    MemberAccountRecord memberAccountRecord = new MemberAccountRecord();
                    BeanUtils.copyProperties(memberAccount, memberAccountRecord);
                    //支付的账户类型 0个人钱包 1 企业钱包 2权益金 3收益金
                    //编码规则(22位): 支付方式(1位:R)+ 时间戳到毫秒17位+uuid后4位
                    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmssSSS");
                    String timeStamp = dateFormat.format(System.currentTimeMillis());
                    String num = "G" + timeStamp + StringUtils.right(UUID.randomUUID().toString(), 4);
                    memberAccountRecord.setLocalTradeNo(num);
                    memberAccountRecord.setAccountType("0");
                    //记录类型(0会员在线充值,1支出,2转账收入,3分配余额,4后台订单调整,5平台赠送,6积分兑换 7回收金额 8平台钱包充值 9分销返利 10资源占用费 11平台扣费 12 数据迁移 13共享额度变更 14后台退款 15.原路退款 16原路返还 ) 17.先付后退充值 18.先付后退退款
                    memberAccountRecord.setRecordType("5");
                    //本次变更金额
                    memberAccountRecord.setAmount(new BigDecimal(marketActivityRecord.getAwardAmount()));
                    memberAccountRecord.setResult(memberAccount.getAccount());
                    memberAccountRecord.setRemark("平台赠送");
                    memberAccountRecord.setCreatedTime(new Date());
                    memberAccountRecord.setLastUpdatedTime(new Date());

                    memberAccountRecordMapper.insertByReturnId(memberAccountRecord);
                    // 发送mq 给后台
                    mqProducer.send(MqConfig.app_rc_operator_account_record, JSON.toJSONString(memberAccountRecord));
                    marketActivityMember.setGainCount(marketActivityMember.getGainCount()+1);
                    marketActivityMemberService.updateByPrimaryKey(marketActivityMember);
                    //MarketActivityMember marketActivityMember = marketActivityMemberAdd2(memberInfo, marketActivityRecord.getMarketActivityId(), null, "5");
                }

                //活动送优惠券
                if (marketActivityRecord.getTicketTypeId() != null) {
                    TenantTicketType tenantTicketType = tenantTicketTypeMapper.selectByPrimaryKey(marketActivityRecord.getTicketTypeId());
                    if (tenantTicketType != null) {
                        //MarketActivityMember marketActivityMember = marketActivityMemberAdd2(memberInfo, marketActivityRecord.getMarketActivityId(), null, "5");
                        marketActivityMember.setGainCount(marketActivityMember.getGainCount()+1);
                        marketActivityMemberService.updateByPrimaryKey(marketActivityMember);
                        //MarketActivityMember marketActivityMember=marketActivityMemberService.selectByAcitvity(marketActivity.getMarketActivityId(),memberInfo.getMemberId());
                        allTicketDataAdd(memberInfo, tenantTicketType, 1, null, marketActivityMember);
                    }
                }
            }

        }


    }

    /**
     * 充值活动
     *
     * @param memberId
     */
    @Override
    public void rechangerMember(Long memberId, RechargeOrder rechargeOrder) {
        //查看用户可以参与的活动(拥有参与次数的)
        MemberInfo memberInfo = memberInfoMapper.selectByPrimaryKey(memberId);

        List<MarketActivity> listActivityRule = marketActivityMapper.listActivityRuleWithGiveJoin(null, memberInfo.getTenantCode(), memberInfo.getMemberId())
                .stream().filter(data -> "1".equals(data.getActivityType())).collect(Collectors.toList());
        List<Long> ids = listActivityRule.stream().map(MarketActivity::getMarketActivityId).collect(Collectors.toList());
        List<MarketActivityRecord> marketActivityRecordList = new ArrayList<>();

        if (ids.size() > 0) {
            //活动明细
            MarketActivityRecordExample marketActivityRecordExample = new MarketActivityRecordExample();
            marketActivityRecordExample.createCriteria().andMarketActivityIdIn(ids);
            marketActivityRecordList = marketActivityRecordService.selectByExample(marketActivityRecordExample);
        }

        for (MarketActivity marketActivity : listActivityRule) {
            //3.充值活动参与
            //4.数据录入（送优惠券，送金额）
            List<MarketActivityRecord> currentList = marketActivityRecordList.stream()
                    .filter(data -> "3".equals(data.getGearType())
                            && marketActivity.getMarketActivityId().equals(data.getMarketActivityId())
                            && data.getChargeAmount() != null).collect(Collectors.toList());

            //活动次数
            MarketActivityMemberExample marketActivityMemberExample = new MarketActivityMemberExample();
            marketActivityMemberExample.createCriteria()
                    .andMemberIdEqualTo(memberId)
                    .andMarketActivityIdEqualTo(marketActivity.getMarketActivityId());
            MarketActivityMember marketActivityMember=marketActivityMemberMapper.selectByExample(marketActivityMemberExample).stream().findFirst().orElseGet(()->null);

            //活动期间内的充值额度
            List<MemberAccountRecord> memberAccountList = memberAccountRecordService.listPayByTime(memberId, marketActivity.getBeginTime(), marketActivity.getEndTime());
            BigDecimal allAmount = memberAccountList.stream().map(MemberAccountRecord::getAmount).reduce(BigDecimal.ZERO, BigDecimal::add);

            //参与次数不能大于总量
            if (marketActivityMember!=null&&currentList.size() <marketActivityMember.getGainCount()) {
                continue;
            }
            //按照金额排序
            List<MarketActivityRecord> sortList = currentList.stream().sorted(Comparator.comparing(MarketActivityRecord::getChargeAmount)).collect(Collectors.toList());
            MarketActivityRecord marketActivityRecord = sortList.get(marketActivityMember.getGainCount()-1);

            //判断 累充条件(0:活动期间内满足,1:一次性满足 默认0
            if ("0".equals(marketActivity.getSumCondition())) {
                //累计 不满足
                if (allAmount.compareTo(new BigDecimal(marketActivityRecord.getChargeAmount())) < 0) {
                    continue;
                }

            } else {
                //一次性不满足
                if (rechargeOrder == null || rechargeOrder.getAmount().compareTo(new BigDecimal(marketActivityRecord.getChargeAmount())) < 0) {
                    continue;
                }
            }

            //活动送金额
            if (marketActivityRecord.getAwardAmount() != null) {
                MemberAccount memberAccount = memberAccountService.selectByPrimaryKey(memberId);
                memberAccount.setAccount(memberAccount.getAccount().add(new BigDecimal(marketActivityRecord.getAwardAmount())));
                memberAccount.setAllRechargeAmount(memberAccount.getAllRechargeAmount().add(new BigDecimal(marketActivityRecord.getAwardAmount())));
                memberAccount.setLastUpdatedTime(new Date());
                memberAccountService.updateByPrimaryKeySelective(memberAccount);

                //3 新增余额变动记录
                MemberAccountRecord memberAccountRecord = new MemberAccountRecord();
                BeanUtils.copyProperties(memberAccount, memberAccountRecord);
                //支付的账户类型 0个人钱包 1 企业钱包 2权益金 3收益金
                memberAccountRecord.setAccountType("0");
                //记录类型(0会员在线充值,1支出,2转账收入,3分配余额,4后台订单调整,5平台赠送,6积分兑换 7回收金额 8平台钱包充值 9分销返利 10资源占用费 11平台扣费 12 数据迁移 13共享额度变更 14后台退款 15.原路退款 16原路返还 ) 17.先付后退充值 18.先付后退退款
                memberAccountRecord.setRecordType("5");
                //本次变更金额
                //编码规则(22位): 支付方式(1位:R)+ 时间戳到毫秒17位+uuid后4位
                SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmssSSS");
                String timeStamp = dateFormat.format(System.currentTimeMillis());
                String num = "G" + timeStamp + StringUtils.right(UUID.randomUUID().toString(), 4);
                memberAccountRecord.setLocalTradeNo(num);
                memberAccountRecord.setAmount(new BigDecimal(marketActivityRecord.getAwardAmount()));
                memberAccountRecord.setResult(memberAccount.getAccount());
                memberAccountRecord.setRemark("平台赠送");
                memberAccountRecord.setCreatedTime(new Date());
                memberAccountRecord.setLastUpdatedTime(new Date());
                memberAccountRecordMapper.insertByReturnId(memberAccountRecord);
                // 发送mq 给后台
                mqProducer.send(MqConfig.app_rc_operator_account_record, JSON.toJSONString(memberAccountRecord));

                marketActivityMember.setGainCount(marketActivityMember.getGainCount()+1);
                marketActivityMemberService.updateByPrimaryKey(marketActivityMember);
            }

            //活动送优惠券
            if (marketActivityRecord.getTicketTypeId() != null) {
                TenantTicketType tenantTicketType = tenantTicketTypeMapper.selectByPrimaryKey(marketActivityRecord.getTicketTypeId());
                if (tenantTicketType != null) {
                    //MarketActivityMember marketActivityMember = marketActivityMemberAdd2(memberInfo, marketActivityRecord.getMarketActivityId(), null, "1");
                    marketActivityMember.setGainCount(marketActivityMember.getGainCount()+1);
                    marketActivityMemberService.updateByPrimaryKey(marketActivityMember);
                    //MarketActivityMember marketActivityMember=marketActivityMemberService.selectByAcitvity(marketActivity.getMarketActivityId(),memberInfo.getMemberId());
                    allTicketDataAdd(memberInfo, tenantTicketType, 1, null, marketActivityMember);
                }
            }


        }
    }

    public MarketActivityMember marketActivityMemberAdd(MemberInfo memberInfo, Long marketActivityId, Long rechargeOrderId) {
        //MarketActivityMember记录+1 营销活动记录增加
        MarketActivityMember marketActivityMember = new MarketActivityMember();
        marketActivityMember.setTenantCode(memberInfo.getTenantCode());
        marketActivityMember.setMemberId(memberInfo.getMemberId());

        marketActivityMember.setMarketActivityId(marketActivityId);
        //一个营销活动多张优惠券时不录入id
        //marketActivityMember.setTicketTypeId(tenantTicketType.getTicketTypeId());
        marketActivityMember.setGainCount(1);
        marketActivityMember.setCreatedTime(new Date());
        marketActivityMember.setCreatedBy(memberInfo.getTenantCode());
        marketActivityMember.setRechargeOrderId(rechargeOrderId);
        marketActivityMemberService.insertRetrunId(marketActivityMember);
        //marketActivityMemberMapper.insertReturnId(marketActivityMember);
        return marketActivityMember;

    }

    public MarketActivityMember marketActivityMemberAdd2(MemberInfo memberInfo, Long marketActivityId, Long rechargeOrderId, String activityType) {
        //MarketActivityMember记录+1 营销活动记录增加
        MarketActivityMember marketActivityMember = new MarketActivityMember();
        marketActivityMember.setTenantCode(memberInfo.getTenantCode());
        marketActivityMember.setMemberId(memberInfo.getMemberId());

        marketActivityMember.setMarketActivityId(marketActivityId);
        //一个营销活动多张优惠券时不录入id
        //marketActivityMember.setTicketTypeId(tenantTicketType.getTicketTypeId());
        marketActivityMember.setGainCount(1);
        marketActivityMember.setCreatedTime(new Date());
        marketActivityMember.setCreatedBy(memberInfo.getTenantCode());
        marketActivityMember.setRechargeOrderId(rechargeOrderId);
        marketActivityMember.setActivityType(activityType);
        marketActivityMemberService.insertRetrunId(marketActivityMember);
        //marketActivityMemberMapper.insertReturnId(marketActivityMember);
        return marketActivityMember;

    }

    //优惠劵记录增加，发送记录增加，营销活动记录增加
    public void allTicketDataAdd(MemberInfo memberInfo, TenantTicketType tenantTicketType, int count, Long rechargeOrderId, MarketActivityMember marketActivityMember) {
        //发送记录增加
        TenantTicketSendRecord tenantTicketSendRecord = new TenantTicketSendRecord();
        tenantTicketSendRecord.setTenantCode(memberInfo.getTenantCode());
        tenantTicketSendRecord.setActivityMemberId(marketActivityMember.getActivityMemberId());
        tenantTicketSendRecord.setTicketTypeId(tenantTicketType.getTicketTypeId());
        tenantTicketSendRecord.setSendCount(count);
        tenantTicketSendRecord.setSendTime(new Date());
        tenantTicketSendRecord.setSendType("0");
        tenantTicketSendRecord.setCreatedBy(memberInfo.getTenantCode());
        tenantTicketSendRecord.setCreatedTime(new Date());
        tenantTicketSendRecordMapper.insertReturnId(tenantTicketSendRecord);

        //优惠券发放次数 优惠劵记录增加
        insertTicketData(tenantTicketType, count, memberInfo, tenantTicketSendRecord);

    }

    public void insertTicketData(TenantTicketType ticketType, int count, MemberInfo memberInfo, TenantTicketSendRecord tenantTicketSendRecord) {
        if (ticketType != null) {
            for (int i = 0; i < count; i++) {
                Calendar calendar = Calendar.getInstance();
                MemberTicket memberTicket = new MemberTicket();
                memberTicket.setMemberId(memberInfo.getMemberId());
                memberTicket.setTicketTypeId(ticketType.getTicketTypeId());
                memberTicket.setGainTime(new Date());
                if (WebConstant.CON0.equals(ticketType.getEffectType())) {
                    calendar.add(Calendar.DAY_OF_MONTH, ticketType.getEffectDay());
                    memberTicket.setEndTime(calendar.getTime());
                } else {
                    memberTicket.setEndTime(ticketType.getEffectEndDate());
                }
                memberTicket.setTicketSendRecordId(tenantTicketSendRecord.getTicketSendRecordId());
                memberTicket.setStatus(WebConstant.CON0);
                memberTicket.setTicketSource(WebConstant.CON0);
                memberTicket.setCreatedBy(String.valueOf(memberInfo.getMemberId()));
                memberTicket.setCreatedTime(new Date());
                memberTicket.setTenantCode(memberInfo.getTenantCode());
                memberTicketMapper.insertSelective(memberTicket);

                //减少剩余次数
                ticketType.setRemainTicket(ticketType.getRemainTicket() - 1);
                ticketType.setTotalTicket(ticketType.getTotalTicket() + 1);
                ticketType.setLastUpdatedTime(new Date());
                tenantTicketTypeMapper.updateByPrimaryKey(ticketType);
            }
        }
    }
}
